/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-13  @author lizhen
 */

package jwt

import (
	"encoding/base64"
	"encoding/json"
	"time"
)

type dto struct {
	Token     string    `json:"token"`
	ExpiresIn int       `json:"expiresIn"`
	IssuedAt  time.Time `json:"issuedAt"`
	UserID    int       `json:"userID"`
}

func (t dto) String() string {
	c, _ := json.Marshal(t)
	return string(c)
}

type cryptor interface {
	Encrypt(content []byte) (encrypted []byte, err error)
	Decrypt(encrypted []byte) (content []byte, err error)
}

type info struct {
	Username string `json:"username"`
	Token    string `json:"token"`
	UserID   int    `json:"userId"`
}

func (i info) GetUserID() int {
	return i.UserID
}

func (i info) GetUserName() string {
	return i.Username
}

func (i info) GetUserToken() string {
	return i.Token
}

func encryptLoginInfo(i *info, cryptor cryptor) (encrypted string, err error) {
	var buffer []byte
	if buffer, err = json.Marshal(i); err != nil {
		return
	}
	if buffer, err = cryptor.Encrypt(buffer); err != nil {
		return
	}
	encrypted = base64.StdEncoding.EncodeToString(buffer)
	return
}

func decryptLoginInfo(encrypted string, cryptor cryptor) (decrypted *info, err error) {
	var buffer []byte
	buffer, err = base64.StdEncoding.DecodeString(encrypted)
	if err != nil {
		return
	}
	if buffer, err = cryptor.Decrypt(buffer); err != nil {
		return
	}
	var t info
	if err = json.Unmarshal(buffer, &t); err != nil {
		return
	}
	decrypted = &t
	return
}
